package com.bwie.system.service.impl;

import com.bwie.common.doamin.dto.LoginDTO;
import com.bwie.common.doamin.dto.RegisterDTO;
import com.bwie.common.doamin.model.SysUser;
import com.bwie.common.exceptions.BizException;
import com.bwie.system.mapper.SysUserMapper;
import com.bwie.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author <a href="mailto:2943147140@qq.com">刘洋朔</a>
 * @version 1.0
 * @description:
 * @date 2025/9/9 10:50
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    /**
     * 用户控制层
     */
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 卡夫卡
     */
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * redis
     */
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取登录的用户信息
     * @param loginDTO
     * @return
     */
    @Override
    public SysUser selLoginInfo(LoginDTO loginDTO) {
        return sysUserMapper.selectLoginInfo(loginDTO);
    }

    /**
     * 用户注册
     * @param registerDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(RegisterDTO registerDTO) {
        //点击注册，校验验证码是否正确（2分）
        String phone = registerDTO.getPhone();
        Boolean hasKey = redisTemplate.hasKey("code:" + phone);
        if(!hasKey){
            throw new BizException("验证码错误,请重新输入");
        }
        //用户名称英文字母大小写、数字,长度在6-15位（1分）
        String username = registerDTO.getUsername();
        if(!username.matches("^.*(?=.*[A-z])(?=.*[0-9]).{6,15}$")){
            throw new BizException("用户名称格式不对");
        }
        //注册，添加用户
        //唯一校验
        int count =  sysUserMapper.selSinglePhone(phone);
        if(count > 0){
            throw new BizException("手机号已绑定其他账号,请更换手机号或者解绑");
        }
        //确认无误进行新增用户
        sysUserMapper.insertNewUser(registerDTO);
        //为新用户绑定角色
        Long userId = registerDTO.getId();
        //默认为普通用户，后续需要管理员进行角色干涉
        sysUserMapper.insertNewRole(userId);
        //注册成功后
        //注册成功系统使用MQ异步通知优惠券系统，自动给用户发送满10.01元减10元的新人优惠券（2分）
        kafkaTemplate.send("sendCoupon",registerDTO.getId());
    }

    /**
     * 获取登录的角色id
     * @param userId
     * @return
     */
    @Override
    public Long selRoleByUserId(Long userId) {
        //获取登录的角色id
        return sysUserMapper.selRoleByUserId(userId);
    }
}
